package 第四周;

import java.util.List;

/**
 * @author xhw
 */

public class 删除链表的倒数第n个节点 {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public void main(String[] args) {
//        ListNode head = new ListNode(1);
//        head.next = new ListNode(2);
//        head.next.next = new ListNode(3);
//        ListNode listNode = new ListNode(4);
        ListNode listNode = new ListNode(4);
        ListNode head = new ListNode(
                1, new ListNode(2,
                new ListNode(3, listNode)));

        head = removeNthFromEnd(head, 2);

        // 打印最终的链表
        while (head != null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
        System.out.println("null");
    }

    private ListNode removeNthFromEnd(ListNode head, int n) {
        // 添加一个哑节点（dummy node），它的next指针指向头节点
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode first = dummy;
        ListNode second = dummy;
        // 移动first指针，使其与second指针之间相隔n个节点
        for (int i = 1; i <= n + 1; i++) {
            first = first.next;
        }
        // 同时移动first和second指针，直至first指针到达末尾
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        // 删除second指针的下一个节点（即倒数第n个节点）
        second.next = second.next.next;
        return dummy.next; // 返回修改后的链表的头节点
    }
}
